import { Component } from 'react';
import Taro, { Config } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components'
import { connect } from 'react-redux'
import Iconfont from '@/components/Iconfont'
import CouponView from '@/components/CouponView'
import CarInfo from '@/components/CarInfo'
import { staticUrl } from '@/utils'
import { AtButton, AtIcon } from 'taro-ui'
import classnames from 'classnames'
import { getCouponList } from '@/api/coupon'
import { getAnnualCardBalanceList, getRelatedCouponItem } from '@/api/annual'
import { getRedPacketData } from '@/api/redpacket'
import { getUserBalance, getGuaranteedInformation } from '@/api/user'
import { userPolicyItem, insurancePolicyItem } from '@/api/service'
const blueLicense = 'https://static3.jekunauto.com/img/others/blue-license.png'
import dayjs from 'dayjs'
import './index.scss'

const couponIcon1 = staticUrl('/img/user/coupon-icon1.png')
const couponIcon2 = staticUrl('/img/user/coupon-icon2.png')
const StoredIcon = staticUrl('/img/user/stored.png')
const EServerIcon = staticUrl('/img/user/e-service-icon.png')
const redpacketIcon = staticUrl('/img/user/redpacket-icon.png')
const ykImg = staticUrl('/img/service/yk-img.png')
const fxImg = staticUrl('/img/service/fx-img.png')
const bxIcon = staticUrl('/img/service/bx-icon.png')
interface State {
  availableList: any
  userBalance: any
  btnStatus: any
  couponList: any
  repacketInfo: any
  policyList: any,
  serverList: any,
  baobeiInfo: any
	selectStoreCode:Array<any>
  cashBackList: any
}

@connect<any>(({ location, car }) => ({ storeInfo: location.storeLocation, car: car.carInfo.currentCar }))
class Service extends Component<any> {
  constructor (props) {
    super(props)
    if (this.props.car) {
      this.car = this.props.car
    }
    this.state = {
      btnStatus: {
        btnText: '去使用',
        state: 1,
        disabled: true
      },
      availableList: null,
      userBalance: [],//用户储值列表
      couponList: null,
      repacketInfo: null,
      policyList: null,
      serverList: [],
      baobeiInfo: null,
			selectStoreCode:[],
      cashBackList: []
    }
  }


  state: State
  componentDidShow() {
  }

  componentDidMount() {
    // 获取红包
    getRedPacketData().then(res => {
      const data = res.data['data']
      this.setState({
        repacketInfo: data
      })
    })

    this.getGuaranteedInformation()
    //获取用户储值列表
    this.getUserBalance()
    // 获取年卡余额
    this.getAnnualCardBalanceList()
    // 获取卡券
    this.getCouponData()
    // 获取保险油卡
    this.getUserPolicyItem()
    //获取保险返现
    this.getCashBackItem()
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.car.carLicense !== this.car.carLicense) {
      this.car = nextProps.car
      this.getAnnualCardBalanceList()
    }
  }
  private car: ICar | {} = {}
  config: Config = {
    navigationBarTitleText: '我的余额',
    navigationBarTextStyle: 'black',
    navigationBarBackgroundColor: '#fff',
    backgroundColor: '#fff',
  }

  /**
   *获取油卡
   */
  getUserPolicyItem() {
    userPolicyItem({
      query: {
        perPage: 100,
        filter: {
          and: [{ type: { in: [4] } }, { status: { in: [2, 3] } }]
        }
      }
    }).then(res => {
      const data = res.data.data
      this.setState({
        policyList: data
      })
    })
  }
  /**
   * 获取返现
   */
  getCashBackItem() {
    userPolicyItem({
      fields: '*,insurance.projectBelong',
      query: {
        perPage: 100,
        filter: {
          and: [{ type: { in: [3] } }, { status: { in: [2, 8, 9, 10] } }, { projectBelong: 0 }]
        }
      }
    }).then(res => {
      const data = res.data.data.filter(e => e.insurance.projectBelong === 0)
      this.setState({
        cashBackList: data
      })
    })
  }
  /**
   * 跳转返现列表
   */
  toPantCashBack() {
    let path = '/insurance/cashBack'
    Taro.navigateTo({
      url: `/pages/webview/index/index?path=${path}`
    })
  }

  getCouponData() {
    getCouponList({
      type: 1
    }).then(res => {
      const couponList = res.data.data
      this.setState({
        couponList
      })
    })
  }

  // 获取用户储值列表
  getUserBalance() {
    // const STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
    // const { vendorCode } = STORE_LOCATION
    getUserBalance({}).then(res => {
      const data = res.data.data
      this.setState({
        userBalance: data
      })
    })
  }

  // 获取e服务列表
  getGuaranteedInformation() {
    getGuaranteedInformation().then(res => {
      const data = res.data.data
      let list = []
      data.forEach(e => {
        if (e.eMaintain.guaranteeNumber > 0) {
          e.eMaintain.typeList.forEach(v => {
            if (v.guaranteeNumber) {
              list.push({
                type: v.type,
                carLicense: e.carLicense,
                desc: v.desc,
                label: v.label
              })
            }
          })
        }
        if (e.eTyre.guaranteeNumber > 0) {
          e.eTyre.typeList.forEach(v => {
            if (v.guaranteeNumber) {
              list.push({
                type: v.type,
                carLicense: e.carLicense,
                desc: v.desc,
                label: v.label
              })
            }
          })
        }
      })
      this.setState({
        serverList: list
      })
    })
  }

  getAnnualCardBalanceList() {
    getAnnualCardBalanceList({
      type: 1,
      carLicense: this.car.carLicense
    }).then(res => {
      const data = res.data.data
      this.setState({
        availableList: data
      })
    })
  }

  // handleCheck(couponIndex: number) {
  //   let { availableList } = this.state
  //   let coupons = availableList[0].coupons
  //   let couponsItem = coupons[couponIndex]
  //   couponsItem.checked = !couponsItem.checked
  //   this.getRelatedCouponItem(couponsItem)

  // }

	handleCheck(couponIndex: number) {
		let { availableList } = this.state
		let coupons = availableList[0].coupons
		let couponsItem = coupons[couponIndex]
		couponsItem.checked = couponsItem.checked
		this.getRelatedCouponItem(couponsItem)

	}

  async getRelatedCouponItem(couponsItem) {

    let { carLicense, jekunModelCode } = this.car
    let { availableList } = this.state
		// let { carLicense, jekunModelCode } = this.props.car.carInfo.currentCar
		let {	checked, dataMatchRule, timeMark, id, mustRelated, goods, oilProperty } = couponsItem
		let { capacity, goodsId } = goods
		if(checked){ // 取消选中
			let coupons = availableList[0].coupons
			coupons.map(d=>{
				d.checked = false
			})
			this.setState({
				availableList,
			}, () => {
				this.setBtnState()
			})

		}else { // 勾选
			let coupons = availableList[0].coupons
			let usedCoupon = []
			for (let i in coupons) {
				if (coupons[i].checked) {
					usedCoupon.push({
						couponItemId: +coupons[i].id,
						mustUse: coupons[i].mustUse,
						minUse: coupons[i].minUse
					})
				}
			}
			const formData = {
				dataMatchRule,
				timeMark,
				itemId: id,
				mustRelated,
				carLicense,
				jekunModelCode,
				selectGoodsId: goodsId,
				capacity,
				oilProperty,
				usedCoupon,
			}
			try {
				Taro.showLoading({
					title: '关联中',
					mask: true
				})
				let res = await getRelatedCouponItem(formData)
				Taro.hideLoading()
				if (!res.data.success) throw new Error('获取失败请稍后重试')
				this.fillFieldAndCheck(checked, res.data.data)
			} catch (error) {
				Taro.showToast({
					title: error.message,
					icon: 'none',
				})
			} finally {
				//Taro.hideLoading()
			}
		}
  }

	fillFieldAndCheck(checkedStatus, data) {
		let { availableList } = this.state
		let coupons = availableList[0].coupons
		console.log('data',data)
		coupons.map(d=>{
			d.checked = false
		})

		// 首先要将usedCouponItemIds 和 已经勾选的作为对比，然后在
		// usedCouponItemIds.push(data)
		coupons.map(item => {
			for(var i=0;i<data.length;i++){
				if(item.id == data[i].couponItemId){
					item.checked = !checkedStatus
					// item.checked = true
					item.mustUse= data[i].mustUse
					item.minUse= data[i].minUse
				}
			}
		})
		availableList[0].coupons = coupons
		this.setState({
			availableList,
		}, () => {
			this.setBtnState()
		})
	}

  setBtnState() {
    let { availableList, btnStatus } = this.state
    if (availableList.length) {
      btnStatus.state = 2
      btnStatus.btnText = '去使用'
      btnStatus.disabled = true
      let coupons = availableList[0].coupons
      for (let i in coupons) {
        if (coupons[i].checked) {
          btnStatus.disabled = false
        }
      }
    } else {
      btnStatus.disabled = false
    }
    this.setState({
      btnStatus
    })
  }
  // 去使用年卡
  handleSubmit() {
    const { availableList } = this.state
    let coupons = availableList[0].coupons
    let formData: Array<any> = []
    for (let i in coupons) {
      if (coupons[i].checked) {
				if(coupons[i].isCyCheckCoupon == 1){ // 常悦检测新能源流程
					let query = {
						storeCode:coupons[i].belongStoreCode,
						couponId:coupons[i].id
					}
					Taro.navigateTo({ url: `/pages/webview/index/index?path=/check/payment&query=${JSON.stringify(query)}` })
					return
				}
        formData.push({
          couponItemId: coupons[i].id,
          mustUse: coupons[i].mustUse
        })
      }
    }
    Taro.navigateTo({
      url: `/pages/annual/use/index?formData=${JSON.stringify(formData)}`
    })
  }
  // 保险申请
  requestProliy(id) {
    Taro.showModal({
      title: '温馨提示',
      content: '确定提交申请？',
      cancelText: '取消',
      cancelColor: '#999999',
      confirmText: '确定',
      confirmColor: '#12b3ff',
    }).then(res => {
      if (res.confirm) {
        insurancePolicyItem({}, { fields: '*', id }).then(res => {
          this.getUserPolicyItem()
          Taro.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000
          })
        })
      }
    })
  }

  goToCouponDetails(list) {
    Taro.navigateTo({
      url: '/pages/coupon/details/index?id=' + list.id
    })
  }

  // 去办理
  gotoMaintain() {
    let path = '/insurance/upKeep/transact/puls'
    Taro.navigateTo({
      url: `/pages/webview/index/index?path=${path}`
    })
  }

  // 查看更多
  gotoMoreEservice(item) {
    let path = '/maintain/index'
    Taro.navigateTo({
      url: `/pages/webview/index/index?path=${path}`
    })
  }

  // 去使用
  gotoUse(item) {
    let path = '/maintain/detail'
    let query = {
      type: item.type,
      carLicense: item.carLicense
    }
    Taro.navigateTo({ url: `/pages/webview/index/index?path=${path}&query=${JSON.stringify(query)}` })
  }

  gotoLink(e: any, link: string) {
    Taro.navigateTo({
      url: link
    })
  }
  render() {
    const { availableList, userBalance, btnStatus, couponList, repacketInfo, policyList, serverList, cashBackList } = this.state
    const { storeInfo } = this.props
    let cashBackTotal = 0
    cashBackList.forEach(e => {
      cashBackTotal += Number(e.num)
    })
    return (
      <View className='service'>
        <View className='car-view'><CarInfo /></View>
        <View className='card-wrap'>
          {
            serverList.length ? (
              <View className='card-group'>
                <View className='card-hd' onClick={this.gotoMoreEservice}>
                  <View className='text'>
                    <Image className='text-img' src={EServerIcon}></Image>
                    e服务
                  </View>
                  <View className='more'>
                    <View className='span'>查看更多</View>
                    <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
                  </View>
                </View>
                <View>
									{/*

									*/}
                  {
                    serverList.map(v => {
                      return (
                        <View className="e-service-item">
                          <View className="e-service--left">
                            <View className="e-servece-info">
                              <Text className="e-servece--icon"></Text>
                              <Text className="e-service--name">{v.label}</Text>
                              <View className='carinfo-license'>
                                <View className='carinfo-license-bg'>
                                  <Image className='carinfo-license-green' src={blueLicense} mode='widthFix' />
                                </View>
                                <View className='carinfo-license-name'>{v.carLicense}</View>
                              </View>
                            </View>
                            <View className="e-service--sub">{v.desc}</View>
                          </View>
                          <View className="e-service--right" onClick={() => this.gotoUse(v)}>去使用</View>
                        </View>
                      )
                    })
                  }
									{/*  */}

                </View>

              </View>
            ) :  null
              // <View className='card-group'>
              //   <View className='card-hd'>
              //     <View className='text'>
              //       <Image className='text-img' src={EServerIcon}></Image>
              //       e服务
              //     </View>
              //   </View>
              //   <View className="e-service-empty">
              //     <View className="e-empty--name">您当前未办理e服务方案！</View>
              //     <View className="e-empty--desc">500元购两次壳牌全合成保养套餐</View>
              //     <View className="e-empty--btn" onClick={this.gotoMaintain}>去办理</View>
              //   </View>
              // </View>

          }




          <View className='card-group'>
            <View className='card-hd' onClick={() => Taro.navigateTo({ url: '/pages/service/stored/index' })}>
              <View className='text'>
                <Image className='text-img' src={StoredIcon}></Image>
                储值
              </View>
              <View className='more'>
                <View className='span'>查看更多</View>
                <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
              </View>
            </View>
            <View className='card-bd'>
              <View className='redpacket-price'>{userBalance.length > 0 ? (userBalance[0] ? userBalance[0].storageBalance : '0.00') : '0.00'}</View>
              {
                userBalance[0] && userBalance[0].vendorLabel ? <View className='redpacket-store'>{userBalance[0].vendorLabel}可用</View> : null
              }
              <View className='stored-tips'>
                <AtIcon className="stored-tips-icon" value='alert-circle' size='16' color='#FF7026'></AtIcon>
                <View className="stored-tips-text">由于小程序正在升级改造，储值暂不能在小程序支付但您仍可前往门店使用储值消费</View>
              </View>
            </View>
          </View>

          <View className='card-group'>
            <View className='card-hd' onClick={() => Taro.navigateTo({ url: '/pages/redpacket/index/index' })}>
              <View className='text'>
                <Image className='text-img' src={redpacketIcon}></Image>
                红包
              </View>
              <View className='more'>
                <View className='span'>查看更多</View>
                <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
              </View>
            </View>
            <View className='card-bd'>
              <View className='redpacket-price'>{repacketInfo ? repacketInfo.originValue : null}</View>
              <View className='redpacket-store'>{storeInfo ? storeInfo.vendorName : null}</View>
            </View>
          </View>

          {/* <View className='card-group'>
            <View className='card-hd' onClick={() => Taro.navigateTo({ url: '/pages/redpacket/baobei/index' })}>
              <View className='text'>
                <Image className='text-img' src={redpacketIcon}></Image>
                保呗
              </View>
              <View className='more'>
                <View className='span'>查看更多</View>
                <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
              </View>
            </View>
            <View className='card-bd'>
              <View className='redpacket-price'>{baobeiInfo.remainValue}</View>
              <View className='redpacket-store'>全平台适用</View>
            </View>
          </View> */}

          {
            availableList && availableList.length ? (
              <View className='card-group'>
                <View className='card-hd' onClick={() => Taro.navigateTo({ url: '/pages/annual/balance/index' })}>
                  <View className='text'>
                    <Image className='text-img' src={couponIcon2}></Image>
                    年卡
                  </View>
                  <View className='more'>
                    <View className='span'>查看更多</View>
                    <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
                  </View>
                </View>
                {
                  availableList.map(v => {
                    return (
                      <View key={v.storeName} className='content-item-body'>
                        {
                          v.coupons.map((coupon, couponIndex) => {
                            return (
                              <View key={'coupon' + couponIndex} className={classnames('content-item-body-item', {
                                'checked': coupon.checked
                              })} onClick={this.handleCheck.bind(this, couponIndex)}
                              >
                                <View className='content-item-body-item-left'>
                                  <Image className='banner-img' mode='aspectFill' lazyLoad src={coupon.goods.thumbnailUrl}></Image>
                                </View>
                                <View className='content-item-body-item-right'>
                                  <View className='top'>
                                    <Text className='title'>{coupon.goods.goodsName}</Text>
                                    {coupon.goods.tags && <View className='specification'>{coupon.goods.tags.join(',')}</View>}
                                  </View>
																	<View>{coupon.canUsedAreaLabel}</View>
																	<View className='bottom'>
																	<Text className='date'>{`${dayjs.unix(coupon.startAt).format('YYYY年MM月DD日')}-${dayjs.unix(coupon.endAt).format('YYYY年MM月DD日')}`}</Text>
																	</View>
                                  {coupon.count > 0 && <Text className='amount'>x{coupon.count}</Text>}
                                </View>
                              </View>
                            )
                          })
                        }
                      </View>
                    )
                  })
                }
                <View className='annual-btn-wrap'>
                  <AtButton type='primary' disabled={btnStatus.disabled} onClick={this.handleSubmit.bind(this)}>{btnStatus.btnText}</AtButton>
                </View>
              </View>
            ) : null
          }
          {
            // (policyList && policyList.length) || (cashBackList && cashBackList.length) ?
            <View className='card-group'>
              <View className='card-hd'>
                <View className='text'>
                  <Image className='text-img' src={bxIcon}></Image>
                  保险返现
                </View>
              </View>
              <View className='insurance'>
                {
                  <View className='insurance-list'>
                    <View className='insurance-list-content'>
                      <View className='img s2'><Image src={fxImg} mode='widthFix' className='pic'></Image></View>
                      <View className='text-container'>
                        <View className='cash-back-name'>XJ {cashBackTotal}元</View>
                      </View>
                    </View>
                    <View className='btn' onClick={() => this.toPantCashBack()}>申请返现</View>
                  </View>
                }
                {
                  policyList && policyList.length ?
                    policyList.map(policy => {
                      return (
                        <View key={policy.id} className='insurance-list'>
                          <View className='insurance-list-content'>
                            {policy.type === 4 && <View className='img s1'><Image src={ykImg} mode='widthFix' className='pic'></Image></View>}
                            {policy.type === 3 && <View className='img s2'><Image src={fxImg} mode='widthFix' className='pic'></Image></View>}
                            <View className='text-container'>
                              <View className='name'>{policy.title + policy.num}元</View>
                              <View className='sub-name'>{policy.carLicense}</View>
                            </View>
                          </View>
                          {policy.status === 2 && <View className='btn' onClick={() => this.requestProliy(policy.id)}>申请{policy.type === 4 ? '油卡' : '返现'}</View>}
                          {policy.status === 3 && <View className='btn s2'>已提交申请</View>}
                        </View>
                      )
                    }) : null
                }
              </View>
            </View>
            // : null
          }
          {
            couponList && couponList.length ? (
              <View className='card-group'>
                <View className='card-hd' onClick={() => Taro.navigateTo({ url: '/pages/coupon/index/index' })}>
                  <View className='text'>
                    <Image className='text-img' src={couponIcon1}></Image>
                    优惠券
                  </View>
                  <View className='more'>
                    <View className='span'>查看更多</View>
                    <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
                  </View>
                </View>
                <View className='coupon-bd'>
                  <View className='coupon-list'>
                    {couponList.map(v => {
                      return (
                        <CouponView key={v.id} list={v} handleEvent={this.goToCouponDetails.bind(this)} />
                      )
                    })}
                  </View>
                </View>
              </View>
            ) : null
          }
        </View>
        <View className="tips">没有更多记录啦</View>
      </View>
    )
  }
}
export default Service
